<?php
/*
File: common.php

This file is included either explicitly or implicitly in every Pants page. It
loads required includes and classes and defines a few common functions in the
global namespace.

Author:
  Ryan Grove (ryan@wonko.com)

Copyright:
  Copyright (c) 2007 Ryan Grove. All rights reserved.

License:
  New BSD License (http://opensource.org/licenses/bsd-license.php)
*/

$start_time = microtime(true);

// Set the default timezone so PHP doesn't whine when E_STRICT is on.
date_default_timezone_set(date_default_timezone_get());

// Full path to the directory on the server where Pants resides.
define('PANTS_DIR', dirname(__FILE__));

ob_start('sendOutput');

require PANTS_DIR.'/config.php';

if (DEBUG) {
  error_reporting(E_ALL | E_STRICT);
}

require PANTS_DIR.'/constants.php';
require PANTS_DIR.'/exceptions.php';
require PANTS_DIR.'/classes/Pants.php';
require PANTS_DIR.'/classes/PantsDB.php';
require PANTS_DIR.'/classes/PantsObject.php';
require PANTS_DIR.'/classes/PantsArticle.php';
require PANTS_DIR.'/classes/PantsTag.php';

Pants::init();

set_exception_handler('exceptionHandler');

// -- Common Functions ---------------------------------------------------------

/**
 * Loads the specified class on demand.
 *
 * @return bool whether or not the class was successfully loaded
 */
function __autoload($class_name) {
  if (strpos($class_name, '.')) {
    return false;
  }

  require PANTS_DIR.'/classes/'.$class_name.'.php';
  return true;
}

/**
 * Gets the URL of the current page, including the appropriate http:// or
 * https:// protocol prefix.
 *
 * @return string URL of the current page
 */
function getPageUrl() {
  $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
  return $protocol.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}

/**
 * Handles uncaught exceptions by stopping execution and displaying a standard
 * Pants error page. If debug mode is enabled, the full exception message will
 * be displayed; otherwise a generic error message will be shown.
 */
function exceptionHandler($exception) {
  if (DEBUG) {
    Pants::error('Error', $exception->getMessage());
  }
  else {
    Pants::error('Error', 'An error has occurred and the request could not '.
        'be completed. Please try again later.');
  }
}

/**
 * Sends the buffered page to the client, appending an HTML/XML comment
 * containing the execution time of the page.
 *
 * @return string buffered page
 */
function sendOutput($output) {
  global $start_time;
  return $output.= "\n<!-- ".round(microtime(true) - $start_time, 4)." -->";
}
?>